<?php
namespace app\common\middleware;

use core\Middleware;
use core\Context;
use app\common\model\UserModel;
use core\App;

class AuthMiddleware implements Middleware {
    public function handle($request, $next) {
        $user = Context::get('user');

        if ($user) {
            // 检查session中的token是否有效
            if (isset($_SESSION['user_id']) && isset($_SESSION['login_token'])) {
                if (UserModel::verifyLoginToken($_SESSION['user_id'], $_SESSION['login_token'])) {
                    // 验证通过，继续执行
                    return $next($request);
                }
            }
        }

        // Context中没有用户信息，尝试从session加载
        if (isset($_SESSION['user_id']) && isset($_SESSION['login_token'])) {
            if (UserModel::verifyLoginToken($_SESSION['user_id'], $_SESSION['login_token'])) {
                // 验证成功，加载到Context
                Context::set('user', [
                    'id' => $_SESSION['user_id'],
                    'username' => $_SESSION['username']
                ]);
                return $next($request);
            }
        }

        // 未登录，跳转到登录页
        $app = App::getApp();
        header('Location: /open/login?from=' . $app);
        exit;
    }

    /**
     * 验证用户登录状态
     * @return bool 验证结果
     */
    public static function verify() {
        $user = Context::get('user');

        if ($user) {
            // 检查session中的token是否有效
            if (isset($_SESSION['user_id']) && isset($_SESSION['login_token'])) {
                return UserModel::verifyLoginToken($_SESSION['user_id'], $_SESSION['login_token']);
            }
            return false;
        }

        // Context中没有用户信息，尝试从session加载
        if (isset($_SESSION['user_id']) && isset($_SESSION['login_token'])) {
            if (UserModel::verifyLoginToken($_SESSION['user_id'], $_SESSION['login_token'])) {
                // 验证成功，加载到Context
                Context::set('user', [
                    'id' => $_SESSION['user_id'],
                    'username' => $_SESSION['username']
                ]);
                return true;
            }
        }

        return false;
    }
}